<template>
    <div>
        <el-card id="session_score" class="box-card">
            <div slot="header" class="clearfix">
                <span style="font-weight: bold; font-size: 20px;">
                    {{session.ComputeEventName}}{{session.ComputeGroupName}} {{words.types[session.SessionType]}} {{session.SessionName}} 
                    <el-button style="float: right;" type="primary" @click="showCreateDialog()" v-if="authorize(['ROOT','ADMIN'])" :disabled="hasError">创建比赛场次</el-button>
                    <el-button style="float: right;" @click="showExportDialog()" type="primary" :disabled="hasError" v-if="!authorize(['USER'])">导出前N名</el-button>
                    <el-button style="float: right;" type="primary" @click="saveScore()" v-if="authorize(['ROOT','RECORDER'])" :disabled="hasError">保存成绩</el-button>
                    <el-button style="float: right;" type="primary" @click="reviewScore()" v-if="authorize(['ROOT','REVIEWER'])" :disabled="hasError">审核成绩</el-button>
                </span>
            </div>
            <div class="row" v-if="!authorize(['USER'])">
                <div class="col-md-12">
                    <div style="float: right; font-weight: bolder">
                        <span>录入人: </span><u>{{session.Recorder}}</u>
                        <span>录入时间: </span><u>{{session.RecordTime | time}}</u>
                        <span> / 审核人：</span><u>{{session.Reviewer}}</u>
                        <span>审核时间：</span><u>{{session.ReviewTime | time}}</u>
                    </div>
                </div>
            </div>
            <el-table :data="session.SessionCompetes" stripe border style="width: 100%">
                <el-table-column align="center" prop="SortIndex" sortable label="序号" width="80"></el-table-column>
                <el-table-column align="center" prop="Compete.PassportNo" label="通行证" width="130"></el-table-column>
                <el-table-column align="center" label="姓名/团队">
                    <template slot-scope="scope">
                        <span v-if="scope.row.Compete.Passport != null">{{scope.row.Compete.Passport.User.Name}}</span>
                        <span v-if="scope.row.Compete.Team != null">
                            <li class="fa fa-users"></li>
                            {{scope.row.Compete.Team.Name}}({{scope.row.Compete.Team.Leader.User.Name}})
                        </span>
                    </template>
                </el-table-column>                
                <el-table-column align="center" label="国家地区">
                    <template slot-scope="scope">
                        <span v-if="scope.row.Compete.Team!=null">{{scope.row.Compete.Team.Leader.User | location}}</span>
                        <span v-if="scope.row.Compete.Passport!=null">{{scope.row.Compete.Passport.User | location}}</span>                        
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="Compete.MusicName" label="曲目"></el-table-column>
                <el-table-column align="center" :label="session.Jury0" v-if="!authorize(['USER'])">
                    <template slot-scope="scope">
                        <input :id="'SCORE_'+scope.row.SortIndex+'_'+0" type="text" :disabled="readonly" v-model="scope.row.Score0" @keyup.enter="moveNext" @blur="validCheck">
                    </template>
                </el-table-column>
                <el-table-column align="center" :label="session.Jury1+''" v-if="!authorize(['USER'])">
                    <template slot-scope="scope">
                        <input :id="'SCORE_'+scope.row.SortIndex+'_'+1" type="text" :disabled="readonly" v-model="scope.row.Score1" @keyup.enter="moveNext" @blur="validCheck">
                    </template>
                </el-table-column>
                <el-table-column align="center" :label="session.Jury2" v-if="!authorize(['USER'])">
                    <template slot-scope="scope">
                        <input :id="'SCORE_'+scope.row.SortIndex+'_'+2" type="text" :disabled="readonly" v-model="scope.row.Score2" @keyup.enter="moveNext" @blur="validCheck">
                    </template>
                </el-table-column>
                <el-table-column align="center" :label="session.Jury3" v-if="!authorize(['USER'])">
                    <template slot-scope="scope">
                        <input :id="'SCORE_'+scope.row.SortIndex+'_'+3" type="text" :disabled="readonly" v-model="scope.row.Score3" @keyup.enter="moveNext" @blur="validCheck">
                    </template>
                </el-table-column>
                <el-table-column align="center" :label="session.Jury4" v-if="!authorize(['USER'])">
                    <template slot-scope="scope">
                        <input :id="'SCORE_'+scope.row.SortIndex+'_'+4" type="text" :disabled="readonly" v-model="scope.row.Score4" @keyup.enter="moveNext" @blur="validCheck">
                    </template>
                </el-table-column>
                <el-table-column align="center" :label="session.Jury5" v-if="session.Jury5 != null && !authorize(['USER'])">
                    <template slot-scope="scope">
                        <input :id="'SCORE_'+scope.row.SortIndex+'_'+5" type="text" :disabled="readonly" v-model="scope.row.Score5" @keyup.enter="moveNext" @blur="validCheck">
                    </template>
                </el-table-column>
                <el-table-column align="center" :label="session.Jury6" v-if="session.Jury6 != null && !authorize(['USER'])">
                    <template slot-scope="scope">
                        <input :id="'SCORE_'+scope.row.SortIndex+'_'+6" type="text" :disabled="readonly" v-model="scope.row.Score6" @keyup.enter="moveNext" @blur="validCheck">
                    </template>
                </el-table-column>
                <el-table-column align="center" :label="session.Jury7" v-if="session.Jury7 != null && !authorize(['USER'])">
                    <template slot-scope="scope">
                        <input :id="'SCORE_'+scope.row.SortIndex+'_'+7" type="text" :disabled="readonly" v-model="scope.row.Score7" @keyup.enter="moveNext" @blur="validCheck">
                    </template>
                </el-table-column>
                <el-table-column align="center" :label="session.Jury8" v-if="session.Jury8 != null && !authorize(['USER'])">
                    <template slot-scope="scope">
                        <input :id="'SCORE_'+scope.row.SortIndex+'_'+8" type="text" :disabled="readonly" v-model="scope.row.Score8" @keyup.enter="moveNext" @blur="validCheck">
                    </template>
                </el-table-column>
                <el-table-column align="center" label="总成绩" prop="TotalScore" sortable width="100"></el-table-column>
            </el-table>
        </el-card>
        <compete-export-dialog ref="export_dialog"></compete-export-dialog>
        <compete-create-dialog ref="create_dialog"></compete-create-dialog>
    </div>
</template>

<script>

import "babel-polyfill";
import _remove from 'lodash/remove';
import {DeepClone, LocationStringFormatFromUser, TimeFormat}  from 'web/utils';
import CompeteExportDialog from './compete_export_dialog.vue';
import CompeteCreateDialog from './compete_create_dialog.vue';

export default {
    components: {
        CompeteExportDialog,
        CompeteCreateDialog
    },
    filters: {
        location: LocationStringFormatFromUser,
        time: TimeFormat
    },  
    data() {
        return {
            session: {
                SessionCompetes: []
            },
            exportDialogVisible: false,
            createDialogVisible: false,
            hasError: false,
            readonly: true,
            errors: [],
            words: {
                types: {
                   'PRELIMINARY': '初赛',
                   'REMATCH': '复赛',
                   'FINALS': '决赛'
                }
            }
        }
    }, 
    mounted() {   

        // 是否为只读
        this.readonly = !this.authorize(['ROOT', 'RECORDER']);

        this.$SessionService.GetSessionById(this.$route.params.id)
            .then(async ret => {
                if(ret) {
                    // 加载比赛项目词语
                    let eventWord = await this.$DataService.GetWordByCode(ret.CompeteEvent);
                    ret.ComputeEventName = eventWord.WordName;

                    // 加载比赛分组词语
                    let groupWord = await this.$DataService.GetWordByCode(ret.CompeteGroup);
                    ret.ComputeGroupName = groupWord.WordName;

                    // 是否为独奏
                    this.hasSolo = ret.CompeteEvent.indexOf('SOLO') >= 0;

                    this.session = ret;
                    console.log(this.session)
                }
            });
    },
    methods: {
        moveNext(evt) {
            if(this.readonly) return;
            let parts = evt.srcElement.id.split('_');
            let sortIndex = parseInt(parts[1]);
            let index = this.session.SessionCompetes.findIndex(o => o.SortIndex == sortIndex);
            let compete = this.session.SessionCompetes[index];
            this.calcTotalScore(compete);

            let jury_idx = parseInt(parts[2]);
            if (index < (this.session.SessionCompetes.length-1)) {
                index += 1;
            } else {
                jury_idx += 1;
                index = 0;
            }
            compete = this.session.SessionCompetes[index];
            let next = $('#SCORE_' + compete.SortIndex + '_' + jury_idx);
            next.focus();
            next.select();
        },

        calcTotalScore(compete) {
            let min = 99999, max = -99999, sum = 0.0, count = 0;
            for (let i = 0; i < 9; i++) {
                let score = parseFloat(compete['Score'+i]);
                if (score != null && !isNaN(score)) {
                    if (score < min) min = score;
                    if (score > max) max = score;
                    sum += score;
                    count += 1;
                }
                if (count > 2)
                    compete.TotalScore = ((sum - min - max) / (count - 2)).toFixed(1);
            }
        },

        validCheck(evt) {
            if(this.readonly) return;
            var reg = /^\d+(\.\d+)?$/;
            if(evt.srcElement.value.trim() != '' && 
               !reg.test(evt.srcElement.value)) {
                $(evt.srcElement).addClass('error');
                this.errors.push(evt.srcElement.id);
            } else {
                $(evt.srcElement).removeClass('error');
                _remove(this.errors, n => n == evt.srcElement.id);

                // 重新计算总成绩
                let parts = evt.srcElement.id.split('_');
                let sortIndex = parseInt(parts[1]);
                let index = this.session.SessionCompetes.findIndex(o => o.SortIndex == sortIndex);
                let compete = this.session.SessionCompetes[index];
                this.calcTotalScore(compete);
            }
            this.hasError = this.errors.length > 0;
        },

        saveScore() {
            this.$SessionService.SaveScore(this.session.SessionCompetes)
                .then(ret => {
                    let title = `${this.session.ComputeEventName} ${this.session.ComputeGroupName} ${this.words.types[this.session.SessionType]} ${this.session.SessionName}`
                    if (ret) {
                        this.$notify({
                            title: '保存成功',
                            message: title + '比赛成绩保存成功！',
                            type: 'success'
                        });
                        // this.$router.push({path: '/session'});
                    } else {
                        this.$notify({
                            title: '保存失败',
                            message: title + '比赛成绩保存失败！',
                            type: 'error'
                        });
                    }
                })
        },

        reviewScore() {
            this.$SessionService.ModifyReviewer(this.session)
                .then(ret => {
                    let title = `${this.session.ComputeEventName} ${this.session.ComputeGroupName} ${this.words.types[this.session.SessionType]} ${this.session.SessionName}`
                    if (ret) {
                        this.$notify({
                            title: '审核成功',
                            message: title + '比赛审核完成！',
                            type: 'success'
                        });
                        this.$router.push({path: '/session'});
                    }
                })
        },

        showExportDialog() {
            let data = DeepClone(this.session); 
            this.$refs['export_dialog'].showDialog(data);
        }, 

        showCreateDialog() {
            let data = DeepClone(this.session); 
            this.$refs['create_dialog'].showDialog(data);
        }
    }
}
</script>

<style>
#session_score input {
    width: 100%;
    text-align: center;
}

.error {
    border: red 1px solid;
    color: red;
}

#session_score .el-button:first-child {
    margin-left: 10px;
}

#session_score .el-table__body-wrapper {
    overflow: hidden;
}
</style>
